﻿using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using gdlmo.DNN.Modules.Article.Business;
using gdlmo.Common;


namespace gdlmo.DNN.Modules.Article
{
	public abstract class Article : PortalModuleBase, IActionable, IPortable, ISearchable 
	{
		protected System.Web.UI.WebControls.Label plMessage;
		protected System.Web.UI.WebControls.LinkButton cmdFirst;
		protected System.Web.UI.WebControls.LinkButton cmdPrev;
		protected System.Web.UI.WebControls.DropDownList cboPages;
		protected System.Web.UI.WebControls.LinkButton cmdNext;
		protected System.Web.UI.WebControls.LinkButton cmdLast;
		protected System.Web.UI.HtmlControls.HtmlTable tbPage;
		protected System.Web.UI.HtmlControls.HtmlTable tbMore;
		protected System.Web.UI.WebControls.HyperLink lnkMore;
		protected System.Web.UI.WebControls.PlaceHolder phArticles;
		protected System.Web.UI.WebControls.DataGrid dgArticles;
		
		#region Private Member
		private int CategoryId
		{
			get 
			{
				object o = ViewState["CategoryId"];
				if (o == null) 
				{
					return 0;
				}
				return (int)o;
			}

			set 
			{				
				ViewState["CategoryId"] = value;
			}
		}	
		private int MaxChars
		{
			get 
			{
				object o = ViewState["MaxChars"];
				if (o == null) 
				{
					return 10;
				}
				return (int)o;
			}

			set 
			{				
				ViewState["MaxChars"] = value;
			}
		}	
		private int PageSize
		{
			get 
			{
				object o = ViewState["PageSize"];
				if (o == null) 
				{
					return 10;
				}
				return (int)o;
			}

			set 
			{				
				ViewState["PageSize"] = value;
			}
		}	
		/// <summary>
		/// 页索引，从0开始
		/// </summary>
		private int PageIndex
		{
			get 
			{
				object o = ViewState["PageIndex"];
				if (o == null) 
				{
					return 0;
				}
				return (int)o;
			}

			set 
			{				
				ViewState["PageIndex"] = value;
			}
		}
		private int PageCount
		{
			get
			{
				object o = ViewState["PageCount"];
				if (o == null) 
				{
					return 0;
				}
				return (int)o;
			}
			set
			{
				ViewState["PageCount"] = value;
			}
		}
		#endregion

		#region Private Function
		protected int GetMaxChars()
		{
			return MaxChars;
		}
		
//		public static string GetMyURL(string title)
//		{
//			string url = "~/UploadFile/";
//			return url + title;
//		}		
		
		/// <summary>
		/// 是否显示分页
		/// </summary>
		/// <param name="PageShow"></param>
		private void IsPageShow(Boolean PageShow)
		{
			tbPage.Visible = PageShow;
			tbMore.Visible = !tbPage.Visible;
		}
		/// <summary>
		/// 处理按钮
		/// </summary>
		private void ProessButton()
		{
			if (this.PageIndex == 0)
			{
				this.cmdFirst.Enabled = false;
				this.cmdPrev.Enabled = false;
			}
			else
			{
				this.cmdFirst.Enabled = true;
				this.cmdPrev.Enabled = true;
			}
			if (this.PageIndex == (this.PageCount - 1))
			{
				this.cmdNext.Enabled = false;
				this.cmdLast.Enabled = false;
			}
			else
			{
				this.cmdNext.Enabled = true;
				this.cmdLast.Enabled = true;
			}
			if (this.PageCount == 0)
			{
				this.cmdFirst.Enabled = false;
				this.cmdPrev.Enabled = false;
				this.cmdNext.Enabled = false;
				this.cmdLast.Enabled = false;
			}
		}
		private string EditURL(string KeyName, string KeyValue, string ControlKey)
		{
			string sLeft = ControlKey;
			if (string.Compare(sLeft, "", false) == 0)
			{
				sLeft = "Edit";
			}
			if ((string.Compare(KeyName, "", false) != 0) & (string.Compare(KeyValue, "", false) != 0))
			{
				return "";	//DotNetNuke.Common.Globals.NavigateURL(this.ArticleManagerTabID, sLeft, new string[] { "mid=" + this.ArticleManagerModuleID.ToString(), KeyName + "=" + KeyValue });
			}
			return "" ;		//DotNetNuke.Common.Globals.NavigateURL(this.ArticleManagerTabID, sLeft, new string[] { "mid=" + this.ArticleManagerModuleID.ToString() });
		}

		private string ShowLinkUrl(int ArticleID)
		{
//			if(
			if(string.Compare(this.Settings["ShowLinkUrl"].ToString(),"",false)!= 0)
			{				
				return (DotNetNuke.Common.Globals.LinkClickURL(this.Settings["ShowLinkUrl"].ToString()) + "&ArticleID=" + ArticleID.ToString());
//				return (DotNetNuke.Common.Globals.LinkClick(this.Settings["ShowLinkUrl"].ToString()) + "&ArticleID=" + ArticleID.ToString());

				
			}			
			return this.EditUrl("ArticleID", ArticleID.ToString(), "ArticleShow");
		}

		protected string BindXml(ArrayList Articles)
		{
			const string STR_HEADER ="Header";
			const string STR_FOOTER = "Footer";
			const string STR_CONTENT = "Item";
			string XmlFilename = "Template.xml";
			string Header = string.Empty;
			string Footer = string.Empty;
			string Content = string.Empty;
			string strOut = "";

			System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
			XmlDoc.Load(this.Server.MapPath(this.TemplateSourceDirectory + "/XmlPackages/" + XmlFilename));
			Header = XmlDoc.GetElementsByTagName(STR_HEADER).Item(0).InnerText;
			Content = XmlDoc.GetElementsByTagName(STR_CONTENT).Item(0).InnerText;
			Footer = XmlDoc.GetElementsByTagName(STR_FOOTER).Item(0).InnerText;

//			Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant);
			foreach(ArticleInfo article in Articles)
			{					
				strOut = StringHelper.ReplaceEx2(Content,"[Title]",HtmlUtils.Shorten(article.DeptName + "：" + article.Title,this.MaxChars,"...."));
				strOut = StringHelper.ReplaceEx2(strOut,"[LinkUrl]",EditUrl("ArticleID",article.ArticleID.ToString(),"AccesoryList"));
				strOut = StringHelper.ReplaceEx2(strOut,"[Target]","_blank");
				strOut = StringHelper.ReplaceEx2(strOut,"[CreatedDate]",article.CreatedDate.ToShortDateString());									
			}
			strOut = Header + strOut + Footer;
			return strOut;
		}
		protected void BindList()
		{
			ArticleController objArticle = new ArticleController();
//			string Title ,Author , DeptName , Summary,int PageIndex,int PageSize,ref int PageCount 
//			DateTime StartCreatedDate, DateTime EndCreatedDate;
//			int Rcount = objArticle.GetRcount(CategoryId);			
//			if ((Rcount % this.PageSize) > 0)
//			{
//				this.PageCount = (Rcount / this.PageSize) + 1;
//			}
//			else
//			{
//				this.PageCount = Rcount / this.PageSize;
//			}			
			int pcount=0;	
			
			dgArticles.DataSource = objArticle.GetPagingData(CategoryId,this.PageIndex,this.PageSize,ref pcount);
			this.PageCount = pcount;
			if(cboPages.Items.Count!=this.PageCount)
			{
				cboPages.Items.Clear();
				for(int i=0;i<this.PageCount;i++)
				{
					cboPages.Items.Add("第" +(i+1).ToString()+"页");
				}
			}	
			dgArticles.DataBind();
			ProessButton();
			cboPages.SelectedIndex = this.PageIndex;			
			phArticles.Controls.Clear();
			phArticles.Controls.Add(new LiteralControl(BindXml(objArticle.GetPagingData(CategoryId,this.PageIndex,this.PageSize,ref pcount))));
		}
		private void PageBtnClicked(object sender, EventArgs e)					
		{
			string BtnName = ((LinkButton) sender).CommandArgument;			
			if (string.Compare(BtnName, "First", false) == 0)
			{
				this.PageIndex = 0;
			}
			else if (string.Compare(BtnName, "Prev", false) == 0)
			{
				if (this.PageIndex > 0)
				{
					this.PageIndex--;
				}
			}
			else if (string.Compare(BtnName, "Next", false) == 0)
			{
				if (this.PageIndex < (this.PageCount - 1))
				{
					this.PageIndex++;
				}
			}
			else if (string.Compare(BtnName, "Last", false) == 0)
			{
				this.PageIndex = this.PageCount - 1;
			}			
			this.BindList();
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.cmdFirst.Click += new System.EventHandler(this.PageBtnClicked);
			this.cmdPrev.Click += new System.EventHandler(this.PageBtnClicked);
			this.cboPages.SelectedIndexChanged += new System.EventHandler(this.cboPages_SelectedIndexChanged);
			this.cmdNext.Click += new System.EventHandler(this.PageBtnClicked);
			this.cmdLast.Click += new System.EventHandler(this.PageBtnClicked);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		#region Event Handlers

		private void Page_Load(object sender, System.EventArgs e)
		{
			try 
			{
				//ArticleController objArticle = new ArticleController();
				if (!Page.IsPostBack) 
				{
					if(Settings["IsPageShow"]!=null)
					{
						IsPageShow(Convert.ToBoolean(Settings["IsPageShow"]));
					}	
					if (Settings["MaxChars"]!=null)
					{
						MaxChars = Int32.Parse(Settings["MaxChars"].ToString());
					}	
					if (Settings["PageSize"]!=null)
					{
						PageSize = Int32.Parse(Settings["PageSize"].ToString());
					}			
					if(Settings["Category"]==null)		//未指定分类
					{
						dgArticles.Visible = false;
						plMessage.Visible = true;
					}
					else
					{
						CategoryId = Int32.Parse(Settings["Category"].ToString());
						dgArticles.Visible = true;
						plMessage.Visible = false;
//						string[] param = new string[2];
//
//						
						lnkMore.NavigateUrl = EditUrl("CategoryId",Settings["Category"].ToString(),"ListMore");
							
						BindList();
					}									
				}
			}
			catch (Exception exc) 
			{
				Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cboPages_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			//this.PageIndex = Convert.ToInt16(cboPages.SelectedValue)-1;
			this.PageIndex = cboPages.SelectedIndex;
			this.BindList();
		}
		#endregion

		#region Optional Interfaces
		public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions 
		{
			get 
			{
				DotNetNuke.Entities.Modules.Actions.ModuleActionCollection Actions = new DotNetNuke.Entities.Modules.Actions.ModuleActionCollection();
				Actions.Add(GetNextActionID(), Localization.GetString(DotNetNuke.Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), DotNetNuke.Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), false, DotNetNuke.Security.SecurityAccessLevel.Edit, true, false);
				return Actions;
			}
		}

		public string ExportModule(int ModuleID)
		{
			// included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
			return null;
		}

		public void ImportModule(int ModuleID, string Content, string Version, int UserID)
		{
			// included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
		}

		public DotNetNuke.Services.Search.SearchItemInfoCollection GetSearchItems(ModuleInfo ModInfo)
		{
			// included as a stub only so that the core knows this module Implements Entities.Modules.ISearchable
			return null;
		}

		#endregion		

		
	}
}
